$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'order/erporder/list',
        datatype: "json",
        colModel: [
            { label: '操作', name: 'option', width: 70 , align: 'center',title: false,
                formatter:function(value, options, row){
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="return vm.allotOrder(\''+ row.orderNo +'\');">分配</a>') ;
                    return actions.join(' ');
                }
            },
            { label: '标记', name: 'orderTag', index: 'orderTag', width: 70, key: true, align: 'center' ,
                formatter: function (value, options, row) {
                    var orderTag = row.orderTag;
                    if (orderTag == 0){
                        return '<a href="javascript:void(0);" onclick="return vm.orderTagShow(\''+ row.orderNo +'\');">添加标记</a>';
                    }
                    var url = "/statics/img/imageselect/img/"+ orderTag +".png";
                    return '<a href="javascript:void(0);" onclick="return vm.orderTagShow(\''+ row.orderNo +'\');"><img src="'+ url +'"></a>';
                }
            },
            { label: '订单编号', name: 'orderNo', index: 'order_no', width: 120, key: true, align: 'center' },
            { label: '会员名', name: 'memberName', index: 'member_name', width: 120 , align: 'center'},
            { label: '订单总额', name: 'payableAmount', index: 'payable_amount', width: 70 , align: 'center'},
            { label: '订单状态', name: 'productionStatus', index: 'production_status', width: 70 , align: 'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    var userData = $("#" + options.gid).jqGrid('getGridParam', 'userData');
                    $.each(userData.productionStatusEnum, function (index, module) {
                        if (module.id == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
            },
            { label: '平台来源', name: 'source', index: 'source', width: 70 , align: 'center'},
            { label: '下单时间', name: 'orderCreatetime', index: 'order_createtime', width: 120 , align: 'center'},
            { label: '审核人', name: 'auditName', index: 'audit_name', width: 70 , align: 'center'},
            { label: '审核时间', name: 'auditTime', index: 'audit_time', width: 120 , align: 'center'},
            { label: '收货人', name: 'shipName', index: 'ship_name', width: 80 , align: 'center'},
            { label: '联系方式', name: '', index: '', width: 100 , align: 'center',
                formatter: function (value, options, row) {
                    var text = '';
                    if (!isBlank(row.shipMobile)){
                        text = row.shipMobile;
                    }
                    if (!isBlank(row.shipTel)){
                        if (isBlank(text)){
                            text = row.shipTel;
                        }else {
                            text += '，' + row.shipTel;
                        }
                    }
                    return text;
                }
            },
            { label: '省市区', name: 'shipArea', index: 'ship_area', width: 100 , align: 'center'},
            { label: '地址', name: 'shipAddr', index: 'ship_addr', width: 120 , align: 'center'},
            { label: '是否开票', name: 'sendTax', index: 'send_tax', width: 60 , align: 'center',
                formatter: function (value, options, row) {
                    return value == 0 ? '不开票' : '开票';
                }
            },
        ],
        viewrecords: true,
        height: window.innerHeight - 120,
        rowNum: 25,
        rowList : [25,50,75],
        rownumbers: true,
        rownumWidth: 40,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            //枚举参数
            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            vm.e.productionStatusEnum = userData.productionStatusEnum;
            vm.e.goodsTypeEnum = userData.goodsTypeEnum;
        }
    });
    // 显示序号
    $("#jqGrid").jqGrid('setLabel',0, '序号', '{width:80}');
});

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        showOrder: false,
        showLogi: false,
        erporderAllotShowList: false,
        erpOrder: {csId:null,pmcId:null},
        orderInfo: {},
        /* 订单备注 */
        remarkList:{},
        /* 支付信息列表 */
        userPaymentList: [],
        /* 商品列表 */
        erpOrderItemEntityList: [],
        /* 已分配列表 */
        erpOrderProductionList: [],
        /* 客服列表 */
        csIdList:[],
        /* 跟单员列表 */
        pmcIdList:[],
        /* 支付方式（多个逗号隔开） */
        paymentType: null,
        /* 枚举 */
        e:{
            productionStatusEnum: [],
            goodsTypeEnum: []
        },
        /* 查询字段 */
        q:{
            orderNo: '',
            memberName: '',
            productionStatus: '',
            beginCreatetime: '',
            endCreatetime: '',
            orderTag: '',
            isquery: false,
        },
        /* 外协商添加 */
        suppFormVisible: false,
        suppForm: {
            orderId: '',
            eoItemId: '',
            originalItemId: '',
            handleType: 0, // 0：添加外协  1：成本录入
        },
        suppOptions: [],
        /* 外协商选择页面 */
        supplierPageVisible: false,
        /* 外协商分页参数 */
        supplierPage:{
            currPage:1, // 当前页
            pageSize:8, // 分页数
            totalCount:0, // 总条数
            tableData:[], //数据列
        },
        /* 外协商分页查询参数 */
        supplierQuery: {
            supplierName: '',
            contactName: ''
        },
        /* 订单初始化信息展示 */
        relevanceListVisible: false,
        relevanceList: [],
        /* 订单标记 */
        orderTagVisible: false,
        orderTag: {
            orderNo: ''
        },
        itemSendFileTableVisible: false,
        itemSourceFileTableVisible: false,
        itemFile:{
            /* 保证 $.files_up_oss 在当前页面只初始化一次 */
            filesUpOss: false,
            /* 订单商品集合下标标识，获得当前正在操作的商品元素 */
            itemIndex: 0,
            /* 上传文件类型  source：源文件  send：发货图片 */
            itemFileType: 'source',
            /* 源文件上传图片列表 */
            itemSourceFiles: [],
            /* 发货上传图片列表 */
            itemSendFiles: [],
        },
        /* 订单分配信息 */
        orderAllotFormVisible: false,
        orderAllotData: {
            orderNo: '',
            producer: '',
            cost: ''
        },
        /* 商品分配信息 */
        itemAllotVisible: false,
        itemAllotData:{
            erpItemId: null,
            itemId: null,
            itemName: null,
            allotType: null // 分配商品类型 1：报价  2：标品
        },
        /* 工序分配信息 */
        craftsAllotData: {
            orderNo: '',
            erpItemId: '',
            producer: '',
            attributeId: '',
            attributeName: ''
        },
        /* 设计商品添加物流 */
        erpLogisticsEntity: {},      // 发货信息
        orderItemList: [],            // 订单明细
        logisticsItemList: [],      //勾选的订单明细
        showSendDetail: true,       // 是否显示发货明细
        showLogiNo: true,           // 是否显示配送单号
        logisticsTypeList: [],
        allotLoading: false,
    },
    methods: {
        /* 查询订单时间起始 */
        checkBeginDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.beginCreatetime = dp.cal.getNewDateStr();
            }})
        },
        /* 查询订单时间结束 */
        checkEndDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.endCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 按钮查询 */
        query: function () {
            vm.q.isquery = true;
            vm.reload();
        },
        /* 外协成本录入 */
        costFormShow: function (row) {
            vm.suppForm.handleType = 1;
            vm.suppFormShow(row);
        },
        /* 分配外协工厂 */
        suppFormShow: function (row) {
            if(vm.erpOrder.csId == null){
                alert("请选择客服信息！");
                return;
            }else if(vm.erpOrder.pmcId == null){
                alert("请选择跟单员信息！");
                return;
            }
            vm.suppForm.orderId = row.orderNo;
            vm.suppForm.eoItemId = row.eoItemId;
            vm.suppForm.originalItemId = row.originalItemId;
            vm.querySupplierPageList();
            vm.supplierPageVisible = true;
        },
        /* 查询外协商列表 */
        querySupplierPageList: function () {
            var queryData = {
                "limit":vm.supplierPage.pageSize,
                "page":vm.supplierPage.currPage,
                "supplierName": vm.supplierQuery.supplierName,
                "state": "2"
            }
            $.ajax({
                type: "GET",
                url: baseURL + "suppOffline/erpsupplieroffline/list",
                contentType: "application/json",
                data: queryData,
                success: function(r){
                    vm.supplierPage.tableData = r.page.list
                    vm.supplierPage.totalCount = r.page.totalCount
                }
            });
        },
        /*分页数改变*/
        handleSizeChange: function(val) {
            vm.supplierPage.pageSize = val;
            vm.querySupplierPageList();
        },
        /*分页当前页改变改变*/
        handleCurrentChange: function(val) {
            vm.supplierPage.currPage = val
            vm.querySupplierPageList();
        },
        /* 选择外协商 */
        suppFormCheck: function (row) {
            vm.suppForm.supplierId = row.supplierId;
            vm.suppFormVisible = true;
        },
        /* 保存外协商信息 */
        suppFormSave: function () {
            var accessUrl = "order/erporder/suppSave";
            if (vm.suppForm.handleType == 1){
                accessUrl = "order/erporder/costSave";
            }
            var postData = {
                orderId: vm.suppForm.orderId,
                eoItemId: vm.suppForm.eoItemId,
                supplierId: vm.suppForm.supplierId,
                cost: vm.suppForm.cost,
                attributeName: vm.suppForm.attributeName,
                originalItemId: vm.suppForm.originalItemId,
                csRemark: vm.suppForm.csRemark,
                csId: vm.erpOrder.csId,
                pmcId: vm.erpOrder.pmcId
            };
            $.ajax({
                type: "POST",
                url: baseURL + accessUrl,
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function(r){
                    if(r.code === 0){
                        vm.suppFormVisible = false;
                        vm.supplierPageVisible = false;
                        alert('操作成功', function(index){
                            vm.getInfo(vm.suppForm.orderId);
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 分配页面 */
        allotOrder: function(orderNo){
            vm.getInfo(orderNo);
            vm.showList = false;
            vm.showOrder = true;
            vm.showLogi = false;
        },
        /* 订单初始化 */
        orderInit: function () {
            var arr = [ 3, 4, 5];
            var productionStatus = vm.erpOrder.productionStatus;
            if ($.inArray(productionStatus, arr) == -1){
                alert("当前订单状态不允许初始化订单");
                return false;
            }

            this.$confirm('此操作将会清除所有已分配数据！确认初始化？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/erporder/orderInit?orderId=" + vm.erpOrder.orderNo,
                            contentType: "application/json",
                            data: {},
                            success: function(r){
                                if(r.code === 0){
                                    vm.getInfo(vm.erpOrder.orderNo);
                                }else{
                                    var relevanceList = r.relevanceList;
                                    if (typeof relevanceList != 'undefined'){
                                        vm.relevanceList = relevanceList;
                                        vm.relevanceListVisible = true;
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 详情页面 */
        getInfo: function(orderNo){
            $.get(baseURL + "order/erporder/allotInfo/"+orderNo, function(r){
                vm.orderInfo = r.orderInfo;
                vm.erpOrder = r.erpOrder;
                vm.csIdList = r.csIdList;
                vm.pmcIdList = r.pmcIdList;
                vm.remarkList = r.remarkList;
                vm.erpOrderItemEntityList = r.erpOrderItemEntityList;
                vm.erpOrderProductionList = r.erpOrderProductionList;

                var p = [];
                vm.userPaymentList = r.userPaymentList;
                for (var i in vm.userPaymentList){
                    var item = vm.userPaymentList[i];
                    var payName = item.payName;
                    p.push(payName);
                }
                vm.paymentType = p.join(",");
                vm.filesUploadInit();
            });
        },
        /* 文件上传初始化 */
        filesUploadInit: function () {
            Vue.nextTick(function () {
                // DOM 更新后 初始化oss文件上传
                if (vm.itemFile.filesUpOss){
                    return false;
                }
                vm.itemFile.filesUpOss = true;

                // 构造 上传文件按钮ID
                var ids = [];
                var len = vm.erpOrderItemEntityList.length;
                for (var i = 0; i < len; i++){
                    ids.push("upload_source" + i);
                    ids.push("upload_send" + i);
                }

                /* oss上传 */
                $.files_up_oss({
                    id: ids,//按钮id
                    url: "/sys/oss/getSignature",
                    dir: "order/orderimage/",
                    file_type: "jpg,png,gif,psd,ai,cdr,eps,ppt,word,excel,pdf,tiff,rar,zip,7z",
                    size: "2000mb",//mb
                    view_url: window.parent.vm.ossHost
                }, function (index_number, json) {
                    if (json.Status == 'OK'){
                        var name = json.oldFilename.replace(/'/g, '');
                        if (vm.itemFile.itemFileType == 'source'){
                            // 源文件
                            var idx = index_number / 2;
                            var erpOrderItem = vm.erpOrderItemEntityList[idx];
                            var userAccessory = {
                                orderId: vm.erpOrder.originalOrderId,
                                itemId: erpOrderItem.originalItemId,
                                userId: vm.erpOrder.memberId,
                                url: json.filename,
                                name: name,
                                size: json.size,
                                fileType: json.mimeType
                            }

                            $.ajax({
                                type: "POST",
                                url: baseURL + "order/useraccessory/save",
                                contentType: "application/json",
                                data: JSON.stringify(userAccessory),
                                success: function(r){
                                    if(r.code === 0){
                                        vm.getInfo(vm.erpOrder.orderNo);
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            });
                        }else if (vm.itemFile.itemFileType == 'send'){
                            // 发货图片
                            var idx = (index_number - 1) / 2;
                            var erpOrderItem = vm.erpOrderItemEntityList[idx];
                            var postData = {
                                eoItemId: erpOrderItem.eoItemId,
                                otherAccessory: {
                                    imageUrl: json.filename,
                                    name: name,
                                    size: json.size,
                                    fileType: json.mimeType
                                }
                            }

                            $.ajax({
                                type: "POST",
                                url: baseURL + "production/erporderitem/saveOrderItemSendPics",
                                contentType: "application/json",
                                data: JSON.stringify(postData),
                                success: function(r){
                                    if(r.code == 0){
                                        vm.getInfo(vm.erpOrder.orderNo);
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            });
                        }

                    }else {
                        alert("OSS上传失败，请联系后台管理员！");
                    }
                });
            });
        },
        /* 查询重置 */
        reset: function () {
            vm.q.orderNo = '';
            vm.q.memberName = '';
            vm.q.productionStatus = '';
            vm.q.financeStatus = '';
            vm.q.beginCreatetime = '';
            vm.q.endCreatetime = '';
            vm.q.orderTag = '';
            vm.q.isquery = true;
            vm.reload();
        },
        /* 页面重载 */
        reload: function (event) {
            vm.showList = true;
            vm.showOrder = false;
            vm.showLogi = false;
            var isquery = vm.q.isquery;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            if (isquery){
                page = 1;
            }
            vm.q.isquery = false;
            $("#jqGrid").jqGrid('setGridParam',{
                page: page,
                postData:{
                    'orderNo': vm.q.orderNo,
                    'memberName': vm.q.memberName,
                    'productionStatus':vm.q.productionStatus,
                    'financeStatus':vm.q.financeStatus,
                    'beginCreatetime': vm.q.beginCreatetime,
                    'endCreatetime': vm.q.endCreatetime,
                    'orderTag': vm.q.orderTag
                }
            }).trigger("reloadGrid");
        },
        /* 订单标记 */
        orderTagShow: function (orderNo) {
            vm.orderTag.orderNo = orderNo;
            vm.orderTagVisible = true;
        },
        /* 添加订单标记 */
        addOrderTag: function (tag) {
            $.ajax({
                type: "GET",
                url: baseURL + "order/erporder/orderTagChange",
                contentType: "application/json",
                data: {
                    orderNo: vm.orderTag.orderNo,
                    orderTag: tag
                },
                success: function(r){
                    if(r.code == 0){
                        vm.orderTagVisible = false;
                        vm.reload();
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 设计商品分配 */
        designItemAllot: function (row) {
            if(vm.erpOrder.csId == null){
                alert("请选择客服信息！");
                return;
            }else if(vm.erpOrder.pmcId == null){
                alert("请选择跟单员信息！");
                return;
            }
            this.$confirm('此种分配方式不会生成生产单信息', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        var postData = {
                            erpItemId: row.eoItemId,
                            csId: vm.erpOrder.csId,
                            pmcId: vm.erpOrder.pmcId
                        };
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/erporder/allotOrderItemDesign",
                            contentType: "application/json",
                            data: JSON.stringify(postData),
                            success: function(r){
                                if(r.code === 0){
                                    vm.getInfo(vm.erpOrder.orderNo);
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 设计商品取消分配 */
        designItemReset: function (row) {
            this.$confirm('是否确认取消分配', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/erporder/resetOrderItemDesign?eoItemId=" + row.eoItemId,
                            contentType: "application/json",
                            data: null,
                            success: function(r){
                                if(r.code === 0){
                                    vm.getInfo(vm.erpOrder.orderNo);
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 订单分配 */
        orderAllot: function () {
            if(vm.erpOrder.csId == null){
                alert("请选择客服信息！");
                return;
            }else if(vm.erpOrder.pmcId == null){
                alert("请选择跟单员信息！");
                return;
            }
            vm.allotLoading = true;
            window.orderAllotPageVm.loadData({orderNo:vm.erpOrder.orderNo});
        },
        /* 工序分配 */
        craftsAllot: function(value){
            if(vm.erpOrder.csId == null){
                alert("请选择客服信息！");
                return;
            }else if(vm.erpOrder.pmcId == null){
                alert("请选择跟单员信息！");
                return;
            }
            window.craftsAllotPageVm.loadData({
                sellerId: vm.erpOrder.thirdMerchantId,
                orderNo: vm.erpOrder.orderNo,
                totalAmount: vm.erpOrder.totalAmount,
                itemId: value.originalItemId,
                erpItemId: value.eoItemId,
                itemName: value.name,
                productId: value.productId
            });
        },
        /* 商品分配*/
        itemAllot: function(value){
            // 客服、跟单员
            if(vm.erpOrder.csId == null){
                alert("请选择客服信息！");
                return;
            }else if(vm.erpOrder.pmcId == null){
                alert("请选择跟单员信息！");
                return;
            }

            vm.itemAllotData.itemId = value.originalItemId;
            vm.itemAllotData.erpItemId = value.eoItemId;
            vm.itemAllotData.itemName = value.name;
            var addcartBuyType = value.addcartBuyType;
            if (addcartBuyType == 'print' || addcartBuyType == 'fast'){
                vm.itemAllotData.allotType = 1;
            }else {
                vm.itemAllotData.allotType = 2;
            }
            vm.itemAllotVisible = true;
        },
        /* 商品分配选择 */
        itemAllotType: function (type) {
            vm.allotLoading = true;
            vm.itemAllotVisible = false;
            window.itemAllotPageVm.loadData({
                sellerId: vm.erpOrder.thirdMerchantId,
                orderNo: vm.erpOrder.orderNo,
                itemId: vm.itemAllotData.itemId,
                erpItemId: vm.itemAllotData.erpItemId,
                itemName: vm.itemAllotData.itemName,
                allotType: vm.itemAllotData.allotType,
                sellerType: type
            });
        },
        /* 阳逻发货 */
        yangluoSend: function (value) {
            if(vm.erpOrder.csId == null){
                alert("请选择客服信息！");
                return;
            }else if(vm.erpOrder.pmcId == null){
                alert("请选择跟单员信息！");
                return;
            }
            this.$confirm('确认分配到阳逻仓发货?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        var postData = {
                            orderNo: value.orderNo,
                            erpItemId: value.eoItemId,
                            itemId: value.originalItemId,
                            csId: vm.erpOrder.csId,
                            pmcId: vm.erpOrder.pmcId
                        };
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/erporder/allotOrderItemYangluo",
                            contentType: "application/json",
                            data: JSON.stringify(postData),
                            success: function(r){
                                if(r.code == 0){
                                    vm.getInfo(vm.erpOrder.orderNo);
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 订单商品发货图片展示 */
        itemSendPicsShow: function (idx) {
            var sendPics = vm.erpOrderItemEntityList[idx].sendPics;
            $.ajax({
                type: "GET",
                url: baseURL + "otherAccessory/otheraccessory/imageslist?imageUrl=" + sendPics,
                contentType: "application/json",
                success: function(r){
                    if(r.code === 0){
                        vm.itemSendFileTableVisible = true;
                        vm.itemFile.itemIndex = idx;
                        vm.itemFile.itemSendFiles = r.list;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 订单商品源文件展示 */
        itemSourcePicsShow: function (idx) {
            var itemId = vm.erpOrderItemEntityList[idx].originalItemId;
            $.ajax({
                type: "GET",
                url: baseURL + "order/useraccessory/userAccessorys/" + itemId,
                contentType: "application/json",
                data: [],
                success: function(r){
                    if(r.code === 0){
                        vm.itemSourceFileTableVisible = true;
                        vm.itemFile.itemIndex = idx;
                        vm.itemFile.itemSourceFiles = r.list;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 商品发货文件下载 */
        itemSendFileDownload: function (data) {
            window.location.href = baseURL + "otherAccessory/otheraccessory/download/" + data.id;
        },
        /* 商品原文件下载 */
        itemSourceFileDownload: function (data) {
            window.location.href = baseURL + "order/useraccessory/download/" + data.id;
        },
        /* 商品发货文件删除 */
        itemSendFileDelete: function (data) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        var ids = [data.id];
                        $.ajax({
                            type: "POST",
                            url: baseURL + "otherAccessory/otheraccessory/delete",
                            contentType: "application/json",
                            data: JSON.stringify(ids),
                            success: function(r){
                                if(r.code === 0){
                                    vm.getInfo(vm.erpOrder.orderNo);
                                    vm.itemSendPicsShow(vm.itemFile.itemIndex);
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        // 商品原文件删除
        itemSourceFileDelete: function (data) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        var ids = [data.id];
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/useraccessory/delete",
                            contentType: "application/json",
                            data: JSON.stringify(ids),
                            success: function(r){
                                if(r.code === 0){
                                    vm.getInfo(vm.erpOrder.orderNo);
                                    vm.itemSourcePicsShow(vm.itemFile.itemIndex);
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 分配选项删除 */
        delAllotItem: function (row) {
            this.$confirm('此操作将删除分配信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        var productionId = row.productionId;
                        var orderNo = row.orderNo;
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/erporder/deleteAllotItem?productionId=" + productionId + "&orderId=" + orderNo,
                            contentType: "application/json",
                            success: function(r){
                                if(r.code == 0){
                                    vm.getInfo(vm.erpOrder.orderNo);
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 设计商品添加物流 */
        send: function(orderId){
            var that = this
            $.ajax({
                type: "GET",
                url: baseURL + "order/paperOrder/sendLogisticsInfo?orderId=" + orderId,
                contentType: "application/json",
                data: null,
                success: function(r){
                    if(r.code == 0){
                        vm.erpOrder = r.erpOrder;
                        vm.orderItemList = r.orderItemEntityList;
                        vm.logisticsTypeList = r.logisticsTypeList;
                        that.$refs.multipleTable.toggleAllSelection();
                        vm.erpLogisticsEntity = {
                            toPeople: vm.erpOrder.shipName,
                            toPhone:  vm.erpOrder.shipMobile+""+(vm.erpOrder.shipTel==null?"":","+vm.erpOrder.shipTel),
                            toAddress: vm.erpOrder.shipAddr,
                            toArea: vm.erpOrder.shipArea,
                            toAreaId: vm.erpOrder.shipAreaId,
                            sendType: 3,
                            logiType: 2
                        };

                        vm.showList = false;
                        vm.showOrder = false;
                        vm.showLogi = true;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        // 参数验证
        validator: function () {
            if(vm.erpLogisticsEntity.logiType != 3){
                if (isBlank(vm.erpLogisticsEntity.logisticsId)) {
                    alert("物流方式不能为空");
                    return false;
                }
            }
            if (isBlank(vm.erpLogisticsEntity.toPeople)) {
                alert("收货人不能为空");
                return false;
            } else if (isBlank(vm.erpLogisticsEntity.toAreaId)) {
                alert(" 收货地区不能为空");
                return false;
            } else if (isBlank(vm.erpLogisticsEntity.toArea)) {
                alert("收货地址不能为空");
                return false;
            }
            return true;
        },
        // 物流类型改变
        logiTypeChange: function (value) {
            for (var i = 0, logisticsType; logisticsType = vm.logisticsTypeList[i++];) {
                // 紫云物流 不填写配送单号
                if (logisticsType.logisticsId == value){
                    vm.erpLogisticsEntity.logiCompany = logisticsType.logisticsName;
                    if (logisticsType.logisticsName.indexOf("紫云-") == 0){
                        vm.showLogiNo = false;
                    }
                }else {
                    vm.showLogiNo = true;
                }
            }
        },
        // 监听订单明细勾选change事件
        orderItemSelectionChange: function (row) {
            var list = new Array();
            for (var i = 0, orderItem; orderItem = row[i++];) {
                var logisticsItem = {
                    orderItemId: orderItem.itemId,
                    orderItemName: orderItem.name,
                    quantity: orderItem.nums
                }
                list.push(logisticsItem);
            }
            vm.logisticsItemList = list;
        },
        // 添加物流信息保存
        saveLogistics: function () {
            // 验证参数
            if (!vm.validator()) {
                return false;
            }
            var erpLogisticsDto = {
                erpLogisticsEntity: vm.erpLogisticsEntity,
                erpLogisticsItemList: vm.logisticsItemList
            }
            erpLogisticsDto.erpLogisticsEntity.orderNo = vm.erpOrder.orderNo;
            erpLogisticsDto.erpLogisticsEntity.sellerId = vm.erpOrder.thirdMerchantId;
            erpLogisticsDto.erpLogisticsEntity.orderId = vm.erpOrder.orderNo;
            erpLogisticsDto.erpLogisticsEntity.fromPeople = "ziyun";
            erpLogisticsDto.erpLogisticsEntity.fromArea = "湖北 武汉 江汉区";
            erpLogisticsDto.erpLogisticsEntity.fromAddress = "江汉区常青三路17B9-13";
            erpLogisticsDto.erpLogisticsEntity.fromPhone = "400-000-2519";
            $.ajax({
                type: "POST",
                url: baseURL + "order/orderinfo/saveOrderLogisticsInfo",
                contentType: "application/json",
                data: JSON.stringify(erpLogisticsDto),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        /* 物流发送 */
        sendTypeChange: function (value) {
            if (value == 1) {
                vm.showSendDetail = false;
            } else {
                vm.showSendDetail = true;
            }
        },
        showQuoteItemDetail: function (item) {
            $.get(baseURL + "production/erporderitem/getAllotQuoteItem/" + item.productionId, function(r){
                var orderItem = r.orderItem
                window.itemQuoteDetailVm.loadData({
                    itemId: orderItem.itemId,
                    goodsType: orderItem.goodsType,
                    name: orderItem.name
                })
            });
        },
        /* 商品详情（报价计算过程） */
        showItemDetail: function (item) {
            window.itemQuoteDetailVm.loadData({
                itemId: item.originalItemId,
                goodsType: item.addcartBuyType,
                name: item.name
            })
        },
        /* 格式化报价商品属性显示 */
        formatAddon(row, column, cellValue, index){
            var addcartBuyType = row.addcartBuyType;
            if (addcartBuyType == 'print' || addcartBuyType == 'fast'){
                try {
                    if (typeof JSON.parse(cellValue) == "object"){
                        var jsonObj = JSON.parse(cellValue);
                        var content = '';
                        for (var a in jsonObj){
                            var partsName = jsonObj[a].partsName;
                            var text = partsName + '：';
                            var basicParam = jsonObj[a].basicParam;
                            if (!isBlank(basicParam)){
                                for (var b in basicParam){
                                    text += ' ' + basicParam[b];
                                }
                            }
                            var craftParam = jsonObj[a].craftParam;
                            if (!isBlank(craftParam)){
                                for (var c in craftParam){
                                    text += ' ' + craftParam[c];
                                }
                            }
                            if (a == jsonObj.length - 1){
                                content += text
                            }else {
                                content += text + '，'
                            }
                        }
                        return content;
                    }
                }catch (e){}
            }
            return cellValue;
        },
        /* 报价商品数量从addon中获取 */
        formatNum(row, column, cellValue, index){
            var nums = row.nums;
            var addcartBuyType = row.addcartBuyType;
            if (addcartBuyType == 'print' || addcartBuyType == 'fast'){
                try {
                    if (typeof JSON.parse(row.addon) == "object"){
                        var jsonObj = JSON.parse(row.addon);
                        for (var a in jsonObj){
                            var basicParam = jsonObj[a].basicParam;
                            if (!isBlank(basicParam)){
                                for (var b in basicParam){
                                    if (b == '数量'){
                                        nums = basicParam[b]
                                        break
                                    }
                                }
                            }
                        }
                    }
                }catch (e){}
            }
            return nums;
        }
    }
});
